package com.bjsxt.service.impl;

import com.bjsxt.mapper.MenuMapper;
import com.bjsxt.pojo.Menu;
import com.bjsxt.pojo.PageA;
import com.bjsxt.pojo.TreeA;
import com.bjsxt.service.MenuService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl  implements MenuService {

     @Autowired
     private MenuMapper  menuMapper;

    @Override
    public List<TreeA> findMore(Integer aid, Integer pid) {

        List<Menu> list = menuMapper.selectMore(aid, pid);

        List<TreeA>  li=new ArrayList<>();

        for (Menu  menu:list){

            TreeA  t=new TreeA(menu.getMid(),menu.getMname(),menu.getStatus()==0?"closed":"open",menu.getUrl());

            li.add(t);
        }
        return li;
    }

    @Override
    public PageA<Menu> findAll(Integer page,Integer rows) {

        Page pg = PageHelper.startPage(page, rows);

        List<Menu> list = menuMapper.selectAll();

        PageA<Menu>  pga=new PageA<>(list,pg.getTotal());

        return pga;
    }

    @Override
    public List<TreeA> findAll2(Integer pid) {

        List<Menu> list = menuMapper.selectAll2(pid);
        List<TreeA>  li=new ArrayList<>();
        for (Menu  menu:list){

            TreeA  t=new TreeA(menu.getMid(),menu.getMname(),menu.getStatus()==0?"closed":"open",menu.getUrl());

            li.add(t);
        }
        return li;
    }

    @Override
    public Integer save(Menu menu) {
        return menuMapper.insert(menu);
    }

    @Override
    public Integer change(Menu menu) {
        return menuMapper.update(menu);
    }

    @Override
    public Integer remove(Integer mid) {

        List<Menu> list = menuMapper.selectAll2(mid);

        if(list.size()>0){
            return -1;
        }

        return menuMapper.delete(mid);
    }

    @Override
    public List<TreeA> findAll3() {

        //一级菜单集合
        List<TreeA> list1 = menuMapper.selectAll3(0);

        for(TreeA t:list1){
           //TreeA--一级菜单对象

            //相当于一级菜单mid
            Integer id = t.getId();
            //当前一级 TreeA 下对应的二级菜单 list2
            List<TreeA> list2 = menuMapper.selectAll3(id);
            //把二级菜单保存到一级菜单对象中
            t.setChildren(list2);

        }

        return list1;
    }
}
